﻿using NetEasyMusic.Lib.Details;
using NetEasyMusic.Lib.Models;
using Newtonsoft.Json.Linq;
// ReSharper disable StringLiteralTypo

namespace NetEasyMusic.Lib.Data;

public class Playlist : DataBasic
{
    public Playlist(string cookie) : base(cookie)
    {
    }

    public Playlist()
    {
    }

    public Playlist(string url, bool isUse = false) : base(url, isUse)
    {
    }

    public async Task<List<string>> HighQualityTag()
    {
        var context = await GetFormString("/playlist/highquality/tags");
        return context?["tags"]!.Select(x => x["name"]!.ToObject<string>()!).ToList() ?? [];
    }

    public async Task<PlaylistModel[]> HighQuality(string tag = "全部")
    {
        var context = await GetFormString($"/top/playlist/highquality?cat={tag}&limit=20");
        if (context == null) return [];
        var array = (JArray)context["playlists"]!;
        return array.Select(x => new PlaylistModel(x)).ToArray();
    }

    public async Task<PlaylistDetailModel> GetPlaylist(PlaylistModel model)
    {
        var context = await GetFormString($"/playlist/track/all?id={model.Id}&cookie={Cookie}");
        if (context == null) return new PlaylistDetailModel();
        return new PlaylistDetailModel
        {
            CoverImgUrl = model.CoverImgUrl,
            Name = model.Name, Description = model.Description,
            Musics = context["songs"]!.Select(jsonSong => new SongModel
                {
                    Id = jsonSong["id"]!.ToObject<string>()!,
                    Name = jsonSong["name"]!.ToObject<string>()!,
                    Album = jsonSong["al"]!["name"]!.ToObject<string>()!,
                    AlbumId = jsonSong["al"]!["id"]!.ToObject<string>()!,
                    PicUrl = jsonSong["al"]!["picUrl"]!.ToObject<string>()!,
                    Time = jsonSong["dt"]!.ToObject<string>()!,
                    Artists = jsonSong["ar"]!.Select(jsonAuthor => new ArtistModel
                    {
                        Id = jsonAuthor["id"]!.ToObject<string>()!,
                        Name = jsonAuthor["name"]!.ToObject<string>()!
                    }).ToArray()
                }
            ).ToList()
        };
    }

    public async Task<SongModel[]> GetPlaylistMusic(string id)
    {
        var context = await GetFormString($"/playlist/track/all?limit=12&id={id}");

        return context?["songs"]!.Select(jsonSong => new SongModel
        {
            Id = jsonSong["id"]!.ToObject<string>()!,
            Name = jsonSong["name"]!.ToObject<string>()!,
            PicUrl = jsonSong["al"]!["picUrl"]!.ToObject<string>()!,
            Time = jsonSong["dt"]!.ToObject<string>()!,
            Album = jsonSong["al"]!["name"]!.ToObject<string>()!,
            AlbumId = jsonSong["al"]!["id"]!.ToObject<string>()!
        }).ToArray() ?? [];
    }
}